import React,{useEffect,useState} from 'react';
import {
    SafeAreaView,
    StyleSheet,
    ScrollView,
    View,
    Text,
    DeviceEventEmitter, TextInput, TouchableWithoutFeedback, Keyboard,
} from 'react-native';
import Header from '../../widgets/Header';
import {getffly, setTextThousand} from '../../utils/common';
import screen from '../../utils/screen';
import {useStores} from '../../store';
import {observer} from 'mobx-react';
import {LGBtn} from '../../widgets/buttons';
import RequestUtil from '../../utils/RequestUtil';
import Api from '../../utils/Api';
import {AppModal} from '../../widgets/modal';
import AppEvent from '../../utils/AppEvent';
import Constants from '../../utils/Constants';

const itemW =  (screen.width - screen.PIXEL_150 ) /2
const itemH =  screen.PIXEL_80

export default observer( ({navigation})=>{


    const {userStore} = useStores()
    const [amount,setAmount] = useState('')
    const [data,setData] = useState(null)
    const [selectIndex,setSelectIndex] = useState(0)
    const [order,setOrder] = useState(null)
    useEffect(()=>{
        console.log('recharge',userStore)
        getData()
    },[])

    const getData = ()=>{
        AppModal.showLoading()

        RequestUtil.get(Api.depositList).then(res=>{
            AppModal.hideTip()
            console.log('deposit list',res)
            setData(res.data)
            if(res.data.items.length > 0){
                let defaultMoneyStr = setTextThousand(res.data.items[selectIndex])
                setAmount(defaultMoneyStr)
            }

        },error=>{
            AppModal.hideTip()
            console.log(error)
            AppModal.showError(error.msg)
        })
    }

    const submit = ()=>{
        Keyboard.dismiss()

        let money = amount.replace(/,/g,'')
        if(Number(money) < Number(data.min)){
            const msg = Constants.account.single_recharge_requires + Constants.appsymbol + setTextThousand(data.min)
            AppModal.showTip(msg);
            return
        }
        if(Number(money) > Number(data.max)){
            const msg = Constants.account.single_recharge_requires + Constants.appsymbol + setTextThousand(data.max)
            AppModal.showTip(msg);
            return
        }

        AppModal.showLoading()
        let parma = {amount:money}
        RequestUtil.post(Api.depositOrder,parma,true).then(res=>{
            AppModal.hideTip()
            let data = res.data
            setOrder(data)
            console.log('order',data)

            navigation.push("RechargeSub",{weburl:data.open_url,callback:()=>{
                check()
            }})
        },error=>{
            AppModal.hideTip()
            console.log(error)
            AppModal.showError(error.msg)
        })
    }

    const check = ()=>{
        console.log('check')
        if(!order) return
        AppModal.showLoading()
        let param = {orderId:order.order_id}
        RequestUtil.get(Api.depositQuery,param).then(res=>{
            AppModal.hideTip()
            console.log('deposit check',res)
           let data = res.data
            if(data.status === 1){
                DeviceEventEmitter.emit(AppEvent.update_account)
                navigation.pop()
            }else{
                AppModal.showTip('Recharge failed')
            }

        },error=>{
            AppModal.hideTip()
            console.log(error)
            AppModal.showError(error.msg)
        })
    }

    const renderItem = (item,index)=>{
        const isSelect = selectIndex === index
        const moneyStr = setTextThousand(item)
        return (
            <TouchableWithoutFeedback
                onPress={()=>{
                    setSelectIndex(index)
                    setAmount(moneyStr)
                }}
            >
                <View style={isSelect ? styles.itemSelectBg : styles.itemNormalBg}>
                    <Text style={{fontSize:15,color:isSelect ? '#000' : '#9D9D9D'}}>{Constants.appsymbol} {moneyStr}</Text>
                </View>
            </TouchableWithoutFeedback>
        )
    }

    const getBalanceStr = ()=>{
        return setTextThousand(userStore.userInfo.balance)
    }

    return (
        <View style={styles.container}>
            <Header title={'Recharge'} navigation={navigation}/>
            {
                data && (
                    <ScrollView
                        contentContainerStyle={{
                            paddingVertical: screen.PIXEL_20,
                            paddingHorizontal: screen.PIXEL_40,
                        }}
                    >
                        <Text style={{color:'#FF7012',fontSize:15,textAlign: 'center',marginBottom:screen.PIXEL_40}}>{`${Constants.vip.current_balance} ${Constants.appsymbol} ${getBalanceStr()}`}</Text>

                        {
                            data.enableCustom && (
                                <View>
                                    <Text style={{color:'#000',fontSize:12}}>{'Recharge Amount (KES)'}</Text>

                                    <TextInput
                                        keyboardType='numeric'
                                        allowFontScaling={false}
                                        placeholderTextColor={'rgba(255, 255, 255, 0.35)'}
                                        placeholder={''}
                                        maxLength={30}
                                        style={styles.input}
                                        value={amount}
                                        onChangeText={(text) => {
                                            setAmount(text)
                                        }}
                                    />
                                </View>
                            )
                        }



                        <Text style={{color:'#000',fontSize:12,marginTop: screen.PIXEL_20}}>{'Recommended'}</Text>

                        <View style={{flexDirection:'row',flexWrap:'wrap',justifyContent: 'space-between',marginTop: screen.PIXEL_30}}>
                            {
                                data.items.map((item,index)=>{
                                    return renderItem(item,index)
                                })
                            }
                        </View>

                        {
                            amount.length > 0  ? (
                                <LGBtn
                                    style={{width:'100%',height:screen.PIXEL_90,marginTop:screen.PIXEL_60}}
                                    title={Constants.account.submit}
                                    onPress={()=> submit() }
                                />
                            ) : (
                                <View style={styles.btnGray}>
                                    <Text style={{fontSize: 15,color:'#fff'}}>{Constants.account.submit}</Text>
                                </View>
                            )
                        }

                        <TouchableWithoutFeedback
                            onPress={()=>{
                                navigation.push('History')
                            }}
                        >
                            <View style={[styles.btnGray,{backgroundColor:'#fff',marginTop: screen.PIXEL_20}]}>
                                <Text style={{fontSize: 15,color:'#377C74'}}>{Constants.account.history}</Text>
                            </View>
                        </TouchableWithoutFeedback>
                    </ScrollView>
                )
            }



        </View>
    )
})

const styles= StyleSheet.create({
    container:{
        flex:1,backgroundColor:'#fff'
    },
    content:{
        flex:1,
        paddingHorizontal:screen.PIXEL_60
    },
    input:{
        fontFamily:getffly("bold"), height: screen.PIXEL_90, width: '100%', color: '#377C74', textAlign: 'center', padding: 0, fontSize: 30,
        borderBottomWidth:1,borderBottomColor:'rgba(32,32,32,0.3)'
    },
    btnGray:{
        width:'100%',height:screen.PIXEL_90,marginTop:screen.PIXEL_60,borderRadius:screen.PIXEL_90/2,
        backgroundColor:'#C1C1C1',justifyContent:'center',alignItems:'center'
    },
    itemSelectBg:{
        width:itemW,
        height:itemH,
        justifyContent:'center',
        alignItems: 'center',
        backgroundColor:'rgba(55,124,116,0.26)',
        borderTopLeftRadius:itemH/2,
        borderTopRightRadius: itemH/2,
        borderBottomLeftRadius:itemH/2
    },itemNormalBg:{
        width:itemW,
        height:itemH,
        justifyContent:'center',
        alignItems: 'center',
    }
})
